package com.prometheus.util;

import io.prometheus.client.SimpleCollector;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;

/**
 * @author: Alan
 * @date: 2021/5/18 13:25
 */
public class CustomGauge extends SimpleCollector<CustomGauge.Child> {

    protected CustomGauge(SimpleCollector.Builder b) {
        super(b);
    }

    public static Builder build(String name, String help) {
        return new Builder().name(name).help(help);
    }

    @Override
    public List<MetricFamilySamples> collect() {
        List<MetricFamilySamples.Sample> samples = new ArrayList<>(children.size());
        for (Map.Entry<List<String>, CustomGauge.Child> c : children.entrySet()) {
            samples.add(new MetricFamilySamples.Sample(fullname, labelNames, c.getKey(), getOrDefault(c.getValue().supplier)));
        }
        return familySamplesList(Type.GAUGE, samples);
    }

    @Override
    protected Child newChild() {
        return new Child();
    }

    private static double getOrDefault(Supplier<Double> supplier) {
        Double t = supplier.get();
        if (t == null) {
            return 0D;
        }
        return t;
    }

    public static class Builder extends SimpleCollector.Builder<Builder, CustomGauge> {
        @Override
        public CustomGauge create() {
            return new CustomGauge(this);
        }
    }


    public static class Child {
        private Supplier<Double> supplier = () -> 0.0;

        public void setSupplier(Supplier<Double> supplier) {
            this.supplier = supplier;
        }
    }

}
